package com.yy.job.facade.validator;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import com.yy.job.common.enums.ErrorCodeEnum;
import com.yy.job.core.config.JobConfigXmlContext;
import com.yy.job.core.config.xml.JobXmlConfig;
import com.yy.job.core.config.xml.ModuleXmlConfig;
import com.yy.job.facade.model.YYJobModel;
import com.yy.job.utils.exception.YYJobRuntimeExceptionUtils;

@Service
public class YYJobModelValidator {

	@Resource
	private JobConfigXmlContext jobConfigParser;

	@Autowired
	private YYJobStepModelValidator jobStepModelValidator;

	public void validate(YYJobModel yyJobModel) {
		if (yyJobModel == null) {
			YYJobRuntimeExceptionUtils.throwException(ErrorCodeEnum.CMN_PARAMETER_ERROR, "parameter is null");
		}
		String projectCode = yyJobModel.getProjectCode();
		if (StringUtils.isBlank(yyJobModel.getProjectCode())) {
			YYJobRuntimeExceptionUtils.throwException(ErrorCodeEnum.CMN_PARAMETER_ERROR, "projectCode is null");
		}
		String moduleCode = yyJobModel.getModuleCode();
		if (StringUtils.isBlank(yyJobModel.getModuleCode())) {
			YYJobRuntimeExceptionUtils.throwException(ErrorCodeEnum.CMN_PARAMETER_ERROR, "moduleCode is null");
		}
		String jobCode = yyJobModel.getJobCode();
		if (StringUtils.isBlank(jobCode)) {
			YYJobRuntimeExceptionUtils.throwException(ErrorCodeEnum.CMN_PARAMETER_ERROR, "jobCode is null");
		}
		if(yyJobModel.getJobExecuteType() == null) {
			YYJobRuntimeExceptionUtils.throwException(ErrorCodeEnum.CMN_PARAMETER_ERROR, "jobExecuteType is null");
		}
		if (StringUtils.isBlank(yyJobModel.getBusinessNo())) {
			YYJobRuntimeExceptionUtils.throwException(ErrorCodeEnum.CMN_PARAMETER_ERROR, "businessNo is null");
		}
		if (StringUtils.isBlank(yyJobModel.getOperator())) {
			YYJobRuntimeExceptionUtils.throwException(ErrorCodeEnum.CMN_PARAMETER_ERROR, "operator is null");
		}

		// 根据xml配置来校验
		ModuleXmlConfig findByModuleCode = this.jobConfigParser.getProjectXmlConfig().findByModuleCode(moduleCode);
		if (findByModuleCode == null) {
			YYJobRuntimeExceptionUtils.throwException(ErrorCodeEnum.SUBMIT_MODULE_ERROR, moduleCode, "no module config");
		}

		JobXmlConfig jobConfig = this.jobConfigParser.getProjectXmlConfig().findJobConfig(moduleCode, jobCode);
		if (jobConfig == null) {
			YYJobRuntimeExceptionUtils.throwException(ErrorCodeEnum.SUBMIT_JOB_ERROR, moduleCode, jobCode, "no job config");
		}
		if (!CollectionUtils.isEmpty(jobConfig.getJobStepConfigs()) && CollectionUtils.isEmpty(yyJobModel.getSteps())) {
			YYJobRuntimeExceptionUtils.throwException(ErrorCodeEnum.CMN_PARAMETER_ERROR, "no steps data");
		}

		this.jobStepModelValidator.validate(yyJobModel, yyJobModel.getSteps());
	}

}
